package com.sky.utils;



import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.AccessControlList;
import com.sky.result.Result;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;


/**
 * $
 *
 * @return $
 */
@Data
@AllArgsConstructor
@Slf4j
public class HWeiUtil {
    private String ak;
    private String sk;
    private String endPoint;
    private String bucketName;


    public String uploadFile(MultipartFile file) throws Exception{

        try (InputStream inputStream = file.getInputStream()) {
            // 创建OBS连接
            ObsClient obsClient = new ObsClient(ak, sk, endPoint);

            // 使用UUID生成唯一的文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID().toString() + extension;

            // 将文件上传到OBS
            obsClient.putObject(bucketName, objectName, inputStream);
            // 设置ACL为公共读

            obsClient.setObjectAcl(bucketName, objectName, AccessControlList.REST_CANNED_PUBLIC_READ);

            // 关闭连接
            obsClient.close();

            String url = "http://link.xulonghua.top/" + objectName;
            log.info("文件上传到 {}", url);
            return url;
        } catch (ObsException e) {
            log.error("OBS异常：{}", e.getMessage(), e);
            //Result.error("文件上传失败：" + e.getErrorMessage());
            return "文件上传失败：" + e.getErrorMessage();
        } catch (IOException e) {
            log.error("IO异常：{}", e.getMessage(), e);
            //Result.error("文件上传失败：IO错误");
            return "文件上传失败：IO错误";
        }
    }
}
